const cache = require("./lib/cache");
const axios = require("axios");
const crypto = require('crypto');
const path = require('path');
const {
    allconfig
} = require(path.join(__dirname, './config.js'));

const {
    ipcRenderer
} = require('electron');
const {
    json
} = require("express");
const tokeninfoname = "tokeninfo", //公司移动端的token
    userinfoname = 'userinfo',
    userconfigname = 'userconfig',
    imtokeninfoname = 'imtokeninfo'; //工具服务端的token,这个token要定时刷新
var tokentimer = 0;

var doLogin = function (username, password, rememberme) {
    var retinfo = null;
    return getEpointToken(username, encyptpwd(password)).then((resdata) => {
        var tokeninfo = resdata.custom;
        //记录生成时间
        tokeninfo.createdate = new Date().getTime();
        cache.set(tokeninfoname, tokeninfo);
        return Promise.resolve(tokeninfo.access_token);
    }).then((access_token) => {
        //获取用户信息
        return getEpointUser(access_token).then((resdata) => {
            retinfo = resdata;
            //保存到缓存中
            // resdata.custom.access_token = tokeninfo.access_token;
            if (resdata.custom.photourl) {
                resdata.custom.photourl = allconfig.resturl + "/" + resdata.custom.photourl;
            }
            cache.set(userinfoname, resdata.custom);

            if (resdata.status) {
                //保存用户账号、密码
                this.addUserConfig("username", username);
                this.addUserConfig("password", password);
                this.addUserConfig("rememberme", rememberme);
                return Promise.resolve(resdata.custom);
            } else {
                throw retinfo.text;
            }
        });
    }).then(() => {
        //获取IM的token信息，用来免登
        return getIMToken(username, '11111').then((resdata) => {
            // retinfo = resdata;
            console.log("im信息:" + resdata);
            if (resdata.status) {
                cache.set(imtokeninfoname, resdata.custom);
                //保存用户账号、密码
                return Promise.resolve(resdata.custom);
            } else {
                throw retinfo.text;
            }
        });
    }).catch(msg => {
        throw msg;
    });
}

var dologout = function (afterurl) {
    logout().then((restdata) => {
        var logouturl = afterurl && afterurl.length > 0 ? afterurl : './login.html';
        ipcRenderer.send("loadpage", logouturl);
    });
}


var logout = function (afterurl) {
    //清除缓存信息
    cache.remove(userinfoname);
    return new Promise((resolve, reject) => {
        cache.remove(userinfoname);
        cache.remove(tokeninfoname);
        cache.remove(imtokeninfoname);

        //清除token刷新任务
        clearInterval(tokentimer);
        return resolve(afterurl);
    })
}

var startRefreshToken = function () {
    tokentimer = setInterval(function () {
        refreshIMToken();
    }, 600000);
}

var doLoginbyToken = function (access_token) {
    var retinfo = null;
    //获取用户信息
    return getEpointUser(access_token).then((resdata) => {
        retinfo = resdata;
        //保存到缓存中
        if (resdata.custom.photourl) {
            resdata.custom.photourl = allconfig.resturl + "/" + resdata.custom.photourl;
        }
        cache.set(userinfoname, resdata.custom);
        //包装token信息
        var tokeninfo = {
            "access_token": access_token,
            "generatetime": new Date().getTime()
        }
        cache.set(tokeninfoname, tokeninfo);
        if (resdata.status) {
            return Promise.resolve(resdata.custom.loginid);
        } else {
            throw retinfo.text;
        }
    }).then((loginid) => {
        //获取IM的token信息，用来免登
        return getIMToken(loginid, '11111').then((resdata) => {
            if (resdata.status) {
                //把token信息存储好
                cache.set(imtokeninfoname, resdata.custom);

                return Promise.resolve(resdata.custom);
            } else {
                throw retinfo.text;
            }
        });
    }).then((data) => {

        // localStorage.setItem('fingerprint','莫名其妙的参数fingerprint');
        return Promise.resolve();
    }).catch(msg => {
        throw msg;
    });
}


// 获取 token
function getEpointToken(username, password, plat) {
    var config = {
        method: 'post',
        url: allconfig.ssourl + '/rest/oauth2/token',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        params: {
            client_id: allconfig.epointkey,
            client_secret: allconfig.epointsecret,
            scope: 'basic',
            grant_type: 'password',
            platform: plat ? plat : 'mobile',
            password: password,
            username: username
        },
        data: {}
    };

    return new Promise((resolve, reject) => {
        axios(config)
            .then(response => {
                let retinfo = dealEpointJson(response.data);
                if (retinfo.status) {
                    return resolve(retinfo);
                } else {
                    throw retinfo.text;
                }
            })
            .catch(error => {
                // console.error(error);
                return reject(error);
            });
    })
}


// 获取 token
function getIMToken(username, password) {
    var config = {
        method: 'post',
        url: allconfig.serverurl + '/rest/oauth2/token',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        params: {
            client_id: allconfig.toolepointkey,
            client_secret: allconfig.toolepointsecret,
            scope: 'basic',
            grant_type: 'password',
            platform: 'im',
            password: password,
            username: username
        },
        data: {}
    };

    return new Promise((resolve, reject) => {
        axios(config)
            .then(response => {
                let retinfo = dealEpointJson(response.data);
                if (retinfo.status) {
                    return resolve(retinfo);
                } else {
                    throw retinfo.text;
                }
            })
            .catch(error => {
                // console.error(error);
                return reject(error);
            });
    })
}



// 获取 token
function refreshIMToken() {
    const rtoken = getIMTokenInfo().refresh_token;
    var config = {
        method: 'post',
        url: allconfig.serverurl + '/rest/oauth2/token',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        params: {
            client_id: allconfig.toolepointkey,
            client_secret: allconfig.toolepointsecret,
            grant_type: 'refresh_token',
            refresh_token: rtoken
        },
        data: {}
    };

    axios(config)
        .then(response => {
            //刷新IMToken
            console.log("刷新token：" + JSON.stringify(response));
            let retinfo = dealEpointJson(response.data);
            if (retinfo.status) {
                cache.set(imtokeninfoname, retinfo.custom);
            }
        });
}

function dealEpointJson(responsedata) {
    // console.log(JSON.stringify(str));
    let resdata = responsedata;
    var retinfo = {
        custom: resdata.custom,
        text: resdata.status.text,
        status: resdata.status.code == "1" ? true : false
    };

    return retinfo;
}

// 获取 token
function getEpointUser(access_token) {
    var config = {
        method: 'post',
        url: allconfig.resturl + '/rest/oa9/getuserinfo_guid_v7',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Authorization: 'Bearer ' + access_token
        },
        params: {
            params: {}
        },
        data: {}
    };

    return new Promise((resolve, reject) => {
        axios(config)
            .then(response => {
                let retinfo = dealEpointJson(response.data);
                if (retinfo.status) {
                    return resolve(retinfo);
                } else {
                    throw retinfo.text;
                }
            })
            .catch(error => {
                // console.error(error);
                return reject(error);
            });
    })
}

function encyptpwd(pwd) {
    var md5 = crypto.createHash('sha1');
    var password = md5.update(pwd).digest('hex');
    return password.toLocaleUpperCase();
}

var getUserInfo = function () {
    return cache.get(userinfoname);
}

var getTokenInfo = function () {
    var tokeninfo = cache.get(tokeninfoname);
    return tokeninfo;
}


var getIMTokenInfo = function () {
    var imtokeninfo = cache.get(imtokeninfoname);
    return imtokeninfo;
}

//用户设置
var addUserConfig = function (name, value) {
    var config = cache.get(userconfigname);
    if (config == undefined) {
        config = {};
    }
    config[name] = value;
    cache.set(userconfigname, config);
}

var getUserConfig = function (name) {
    return cache.get(userconfigname) != undefined ? cache.get(userconfigname)[name] : undefined;
}

module.exports.doLogin = doLogin;
module.exports.dologout = dologout;
module.exports.doLoginbyToken = doLoginbyToken;
module.exports.getUserInfo = getUserInfo;
module.exports.getTokenInfo = getTokenInfo;
module.exports.addUserConfig = addUserConfig;
module.exports.getUserConfig = getUserConfig;
module.exports.getIMToken = getIMToken;
module.exports.getIMTokenInfo = getIMTokenInfo;
module.exports.startRefreshToken = startRefreshToken;
